// 全局配置
// const CONFIG = {
//     API_BASE_URL: 'http://localhost:8000',
//     AUTH_SALT: 'GeovisEarth',
//     MAX_FILE_SIZE: 10 * 1024 * 1024, // 10MB
//     SUPPORTED_FORMATS: ['image/jpeg', 'image/png', 'image/webp']
// };

const CONFIG = {
    API_BASE_URL: 'http://101.132.75.167/ai',
    AUTH_SALT: 'GeovisEarth',
    MAX_FILE_SIZE: 10 * 1024 * 1024, // 10MB
    SUPPORTED_FORMATS: ['image/jpeg', 'image/png', 'image/webp']
};

// 状态管理
const state = {
    currentMode: 'generate',
    isGenerating: false,
    currentImage: null,
    currentImageUrl: null,
    generationHistory: []
};

// DOM 元素
const elements = {
    // 模式切换
    modeBtns: document.querySelectorAll('.mode-btn'),
    generatePanel: document.getElementById('generatePanel'),
    createPanel: document.getElementById('createPanel'),
    
    // 图像编辑相关
    uploadArea: document.getElementById('uploadArea'),
    imageInput: document.getElementById('imageInput'),
    imageUrl: document.getElementById('imageUrl'),
    editPrompt: document.getElementById('editPrompt'),
    negativePrompt: document.getElementById('negativePrompt'),
    previewImage: document.getElementById('previewImage'),
    
    // 图片信息显示
    imageInfo: document.getElementById('imageInfo'),
    imageResolution: document.getElementById('imageResolution'),
    imageSize: document.getElementById('imageSize'),
    sizeSelect: document.getElementById('sizeSelect'),
    originalSizeOption: document.getElementById('originalSizeOption'),
    previewPlaceholder: document.getElementById('previewPlaceholder'),
    
    // 图像生成相关
    createPrompt: document.getElementById('createPrompt'),
    createNegativePrompt: document.getElementById('createNegativePrompt'),
    createPreviewImage: document.getElementById('createPreviewImage'),
    createPreviewPlaceholder: document.getElementById('createPreviewPlaceholder'),
    presetBtns: document.querySelectorAll('.preset-btn'),
    
    // 参数设置
    paramsToggle: document.getElementById('paramsToggle'),
    paramsContent: document.getElementById('paramsContent'),
    modelSelect: document.getElementById('modelSelect'),
    stepsSlider: document.getElementById('stepsSlider'),
    stepsValue: document.getElementById('stepsValue'),
    guidanceSlider: document.getElementById('guidanceSlider'),
    guidanceValue: document.getElementById('guidanceValue'),
    seedInput: document.getElementById('seedInput'),
    seedValue: document.getElementById('seedValue'),
    randomSeed: document.getElementById('randomSeed'),
    
    // 控制按钮
    generateBtn: document.getElementById('generateBtn'),
    resetBtn: document.getElementById('resetBtn'),
    
    // 进度和结果
    progressContainer: document.getElementById('progressContainer'),
    progressFill: document.getElementById('progressFill'),
    progressText: document.getElementById('progressText'),
    resultSection: document.getElementById('resultSection'),
    resultImage: document.getElementById('resultImage'),
    downloadBtn: document.getElementById('downloadBtn'),
    copyBtn: document.getElementById('copyBtn'),
    closeResult: document.getElementById('closeResult'),
    
    // 状态指示器
    statusIndicator: document.getElementById('statusIndicator'),
    
    // 通知
    notification: document.getElementById('notification'),
    notificationText: document.getElementById('notificationText')
};

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    setupEventListeners();
    createParticles();
    loadUserPreferences();
});

// 应用初始化
function initializeApp() {
    // 设置默认参数
    updateParameterDisplay();
    
    // 初始化状态指示器
    updateStatusIndicator('ready', '就绪');
    
    // 设置参数面板默认状态
    elements.paramsContent.classList.add('active');
    elements.paramsToggle.classList.add('active');
}

// 事件监听器设置
function setupEventListeners() {
    // 模式切换
    elements.modeBtns.forEach(btn => {
        btn.addEventListener('click', () => switchMode(btn.dataset.mode));
    });
    
    // 文件上传
    elements.uploadArea.addEventListener('click', () => elements.imageInput.click());
    elements.uploadArea.addEventListener('dragover', handleDragOver);
    elements.uploadArea.addEventListener('dragleave', handleDragLeave);
    elements.uploadArea.addEventListener('drop', handleDrop);
    elements.imageInput.addEventListener('change', handleFileSelect);
    
    // URL输入
    elements.imageUrl.addEventListener('input', handleUrlInput);
    
    // 提示词输入
    elements.editPrompt.addEventListener('input', handlePromptInput);
    elements.createPrompt.addEventListener('input', handlePromptInput);
    
    // 风格预设
    elements.presetBtns.forEach(btn => {
        btn.addEventListener('click', () => selectPreset(btn.dataset.style));
    });
    
    // 参数控制
    elements.paramsToggle.addEventListener('click', toggleParamsPanel);
    elements.stepsSlider.addEventListener('input', updateStepsValue);
    elements.guidanceSlider.addEventListener('input', updateGuidanceValue);
    elements.seedInput.addEventListener('input', updateSeedValue);
    elements.randomSeed.addEventListener('click', generateRandomSeed);
    
    // 控制按钮
    if (elements.generateBtn) elements.generateBtn.addEventListener('click', handleGenerate);
    if (elements.resetBtn) elements.resetBtn.addEventListener('click', handleReset);
    
    // 结果操作
    if (elements.downloadBtn) elements.downloadBtn.addEventListener('click', downloadResult);
    if (elements.copyBtn) elements.copyBtn.addEventListener('click', copyResultUrl);
    if (elements.closeResult) elements.closeResult.addEventListener('click', closeResult);
    
    // 键盘快捷键
    document.addEventListener('keydown', handleKeyboard);
}

// 模式切换
function switchMode(mode) {
    state.currentMode = mode;
    
    // 更新按钮状态
    elements.modeBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.mode === mode);
    });
    
    // 更新面板显示
    elements.generatePanel.classList.toggle('active', mode === 'generate');
    elements.createPanel.classList.toggle('active', mode === 'create');
    
    // 更新生成按钮文本
    if (elements.generateBtn) {
        elements.generateBtn.innerHTML = mode === 'generate' 
            ? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>开始编辑'
            : '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/></svg>开始生成';
    }
    
    // 清空当前状态
    clearCurrentState();
}

// 文件拖拽处理
function handleDragOver(e) {
    e.preventDefault();
    elements.uploadArea.classList.add('dragover');
}

function handleDragLeave(e) {
    e.preventDefault();
    elements.uploadArea.classList.remove('dragover');
}

function handleDrop(e) {
    e.preventDefault();
    elements.uploadArea.classList.remove('dragover');
    
    const files = e.dataTransfer.files;
    if (files.length > 0) {
        handleFile(files[0]);
    }
}

// 文件选择处理
function handleFileSelect(e) {
    const file = e.target.files[0];
    if (file) {
        handleFile(file);
    }
}

// 文件处理
async function handleFile(file) {
    // 验证文件类型
    if (!CONFIG.SUPPORTED_FORMATS.includes(file.type)) {
        showNotification('不支持的文件格式，请选择 JPG、PNG 或 WebP 格式', 'error');
        return;
    }
    
    // 验证文件大小
    if (file.size > CONFIG.MAX_FILE_SIZE) {
        showNotification('文件过大，请选择小于 10MB 的图片', 'error');
        return;
    }
    
    try {
        // 显示上传进度
        updateStatusIndicator('uploading', '正在上传图片...');
        showNotification('正在上传图片，请稍候...', 'info');
        
        // 上传文件到后端
        const uploadResult = await uploadFileToServer(file);
        
        if (uploadResult.success) {
            // 保存上传后的URL和文件信息
            state.currentImage = file;
            state.currentImageUrl = uploadResult.file_url;
            state.uploadedFilename = uploadResult.filename;
            
            // 显示预览
            showImagePreview(uploadResult.file_url);
            
            // 显示图片信息
            const dimensions = uploadResult.dimensions || '未知';
            const fileSize = formatFileSize(uploadResult.size || file.size);
            
            elements.imageResolution.textContent = dimensions;
            elements.imageSize.textContent = fileSize;
            elements.imageInfo.style.display = 'block';
            
            // 设置原图分辨率为默认选项
            elements.originalSizeOption.textContent = `原图分辨率 (${dimensions})`;
            elements.originalSizeOption.style.display = 'block';
            elements.originalSizeOption.selected = true;
            
            // 保存原图分辨率到状态
            if (uploadResult.width && uploadResult.height) {
                state.originalDimensions = {
                    width: uploadResult.width,
                    height: uploadResult.height,
                    dimensions: dimensions
                };
            }
            
            updateStatusIndicator('image-loaded', `图片已上传 (${dimensions})`);
            showNotification(`图片上传成功: ${dimensions}`, 'success');
        } else {
            throw new Error(uploadResult.message || '上传失败');
        }
    } catch (error) {
        console.error('文件上传失败:', error);
        showNotification(error.message || '文件上传失败，请重试', 'error');
        updateStatusIndicator('error', '上传失败');
    }
}

// 上传文件到服务器
async function uploadFileToServer(file) {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await fetch(`${CONFIG.API_BASE_URL}/upload`, {
        method: 'POST',
        headers: {
            'X-Auth-Salt': CONFIG.AUTH_SALT
        },
        body: formData
    });
    
    if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || '上传失败');
    }
    
    return await response.json();
}

// URL输入处理
function handleUrlInput(e) {
    const url = e.target.value.trim();
    if (url) {
        state.currentImageUrl = url;
        showImagePreview(url);
        
        // 获取图片分辨率
        const img = new Image();
        img.onload = function() {
            const dimensions = `${img.width} × ${img.height}`;
            
            // 显示图片信息
            elements.imageResolution.textContent = dimensions;
            elements.imageSize.textContent = 'URL图片';
            elements.imageInfo.style.display = 'block';
            
            // 设置原图分辨率为默认选项
            elements.originalSizeOption.textContent = `原图分辨率 (${dimensions})`;
            elements.originalSizeOption.style.display = 'block';
            elements.originalSizeOption.selected = true;
            
            // 保存原图分辨率到状态
            state.originalDimensions = {
                width: img.width,
                height: img.height,
                dimensions: dimensions
            };
            
            updateStatusIndicator('image-loaded', `图片已加载 (${dimensions})`);
            showNotification(`图片分辨率: ${dimensions}`, 'info');
        };
        img.onerror = function() {
            updateStatusIndicator('image-loaded', '图片已加载');
        };
        img.src = url;
    }
}

// 提示词输入处理
function handlePromptInput(e) {
    const prompt = e.target.value.trim();
    if (prompt) {
        updateStatusIndicator('prompt-ready', '提示词已输入');
    }
}

// 风格预设选择
function selectPreset(style) {
    elements.presetBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.style === style);
    });
    
    const presets = {
        realistic: 'A photorealistic image, high quality, detailed, professional photography',
        anime: 'Anime style, manga art, colorful, vibrant, detailed illustration',
        artistic: 'Artistic painting, creative, expressive, unique style, masterpiece',
        cyberpunk: 'Cyberpunk style, futuristic, neon lights, dark atmosphere, sci-fi'
    };
    
    const prompt = presets[style];
    if (state.currentMode === 'create' && elements.createPrompt) {
        elements.createPrompt.value = prompt;
    }
}

// 参数面板切换
function toggleParamsPanel() {
    elements.paramsContent.classList.toggle('active');
    elements.paramsToggle.classList.toggle('active');
}

// 参数值更新
function updateStepsValue() {
    if (elements.stepsSlider && elements.stepsValue) {
        const value = elements.stepsSlider.value;
        elements.stepsValue.textContent = value;
    }
}

function updateGuidanceValue() {
    if (elements.guidanceSlider && elements.guidanceValue) {
        const value = elements.guidanceSlider.value;
        elements.guidanceValue.textContent = value;
    }
}

function updateSeedValue() {
    if (elements.seedInput && elements.seedValue) {
        const value = elements.seedInput.value;
        elements.seedValue.textContent = value;
    }
}

function generateRandomSeed() {
    const seed = Math.floor(Math.random() * 1000000);
    if (elements.seedInput) elements.seedInput.value = seed;
    if (elements.seedValue) elements.seedValue.textContent = seed;
}

function updateParameterDisplay() {
    updateStepsValue();
    updateGuidanceValue();
    updateSeedValue();
}

// 图像预览显示
function showImagePreview(src) {
    const previewImage = state.currentMode === 'generate' 
        ? elements.previewImage 
        : elements.createPreviewImage;
    const placeholder = state.currentMode === 'generate' 
        ? elements.previewPlaceholder 
        : elements.createPreviewPlaceholder;
    const container = state.currentMode === 'generate' 
        ? document.querySelector('.preview-container')
        : document.querySelector('.create-preview-container');
    
    previewImage.src = src;
    previewImage.style.display = 'block';
    placeholder.style.display = 'none';
    
    // 动态调整容器尺寸以适配图片比例
    previewImage.onload = function() {
        const imgWidth = previewImage.naturalWidth;
        const imgHeight = previewImage.naturalHeight;
        const aspectRatio = imgWidth / imgHeight;
        
        // 设置容器的最小和最大尺寸
        const maxWidth = 500;
        const maxHeight = 600;
        const minWidth = 200;
        const minHeight = 200;
        
        let containerWidth, containerHeight;
        
        if (aspectRatio > 1) {
            // 宽图片
            containerWidth = Math.min(maxWidth, Math.max(minWidth, maxWidth));
            containerHeight = containerWidth / aspectRatio;
            if (containerHeight < minHeight) {
                containerHeight = minHeight;
                containerWidth = containerHeight * aspectRatio;
            }
        } else {
            // 高图片
            containerHeight = Math.min(maxHeight, Math.max(minHeight, maxHeight));
            containerWidth = containerHeight * aspectRatio;
            if (containerWidth < minWidth) {
                containerWidth = minWidth;
                containerHeight = containerWidth / aspectRatio;
            }
        }
        
        // 应用动态尺寸
        container.style.width = containerWidth + 'px';
        container.style.height = containerHeight + 'px';
        container.style.aspectRatio = 'unset';
    };
}

// 生成处理
async function handleGenerate() {
    if (state.isGenerating) return;
    
    try {
        // 验证输入
        if (!validateInputs()) return;
        
        // 设置生成状态
        state.isGenerating = true;
        updateGenerateButton();
        showProgress();
        updateStatusIndicator('generating', '正在生成中...');
        
        // 准备请求数据
        const requestData = prepareRequestData();
        
        // 发送请求
        const response = await sendGenerationRequest(requestData);
        
        if (response.ok) {
            const result = await response.json();
            showResult(result);
            updateStatusIndicator('success', '生成完成');
        } else {
            const error = await response.json();
            throw new Error(error.detail || '生成失败');
        }
        
    } catch (error) {
        console.error('生成失败:', error);
        showNotification(error.message || '生成失败，请重试', 'error');
        updateStatusIndicator('error', '生成失败');
    } finally {
        state.isGenerating = false;
        updateGenerateButton();
        hideProgress();
    }
}

// 输入验证
function validateInputs() {
    if (state.currentMode === 'generate') {
        if (!state.currentImageUrl) {
            showNotification('请先上传图片或输入图片URL', 'error');
            return false;
        }
        if (!elements.editPrompt?.value?.trim()) {
            showNotification('请输入编辑提示词', 'error');
            return false;
        }
    } else {
        if (!elements.createPrompt?.value?.trim()) {
            showNotification('请输入生成提示词', 'error');
            return false;
        }
    }
    return true;
}

// 准备请求数据
function prepareRequestData() {
    // 处理尺寸选择
    let size = elements.sizeSelect?.value || '1024x1024';
    if (size === 'original' && state.originalDimensions) {
        size = `${state.originalDimensions.width}x${state.originalDimensions.height}`;
    }
    
    const baseData = {
        model: 'Qwen/Qwen-Image-Edit', // 固定模型
        size: size,
        steps: parseInt(elements.stepsSlider?.value || 50),
        guidance: parseFloat(elements.guidanceSlider?.value || 3.5),
        seed: parseInt(elements.seedInput?.value || 12345),
        negative_prompt: state.currentMode === 'generate' 
            ? elements.negativePrompt?.value || 'lowres, watermark, text artifacts'
            : elements.createNegativePrompt?.value || 'lowres, watermark, text artifacts'
    };
    
    if (state.currentMode === 'generate') {
        return {
            ...baseData,
            prompt: elements.editPrompt?.value || '',
            image_url: state.currentImageUrl
        };
    } else {
        return {
            ...baseData,
            prompt: elements.createPrompt?.value || ''
        };
    }
}

// 发送生成请求
async function sendGenerationRequest(data) {
    const endpoint = state.currentMode === 'generate' ? '/generate' : '/generate_image';
    const url = `${CONFIG.API_BASE_URL}${endpoint}`;
    
    const headers = {
        'Content-Type': 'application/json',
        'X-Auth-Salt': CONFIG.AUTH_SALT
    };
    
    return fetch(url, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(data)
    });
}

// 显示结果
function showResult(result) {
    elements.resultImage.src = result.output_image_url;
    elements.resultImage.alt = '生成结果';
    elements.resultSection.style.display = 'block';
    
    // 更新预览区域（图像生成模式）
    if (state.currentMode === 'create') {
        elements.createPreviewImage.src = result.output_image_url;
        elements.createPreviewImage.style.display = 'block';
        elements.createPreviewPlaceholder.style.display = 'none';
    }
    
    // 保存到历史记录
    state.generationHistory.unshift({
        id: result.task_id,
        mode: state.currentMode,
        prompt: state.currentMode === 'generate' ? (elements.editPrompt?.value || '') : (elements.createPrompt?.value || ''),
        imageUrl: result.output_image_url,
        timestamp: new Date().toISOString()
    });
    
    // 限制历史记录数量
    if (state.generationHistory.length > 10) {
        state.generationHistory = state.generationHistory.slice(0, 10);
    }
    
    // 保存到本地存储
    saveUserPreferences();
}

// 下载结果
function downloadResult() {
    const link = document.createElement('a');
    link.href = elements.resultImage.src;
    link.download = `generated-image-${Date.now()}.jpg`;
    link.click();
}

// 复制结果链接
async function copyResultUrl() {
    const url = elements.resultImage.src;
    if (!url) {
        showNotification('没有可复制的链接', 'error');
        return;
    }

    try {
        // 优先使用现代 Clipboard API
        if (navigator.clipboard && window.isSecureContext) {
            await navigator.clipboard.writeText(url);
            showNotification('链接已复制到剪贴板', 'success');
            return;
        }
        
        // 降级方案：使用传统的 document.execCommand
        const textArea = document.createElement('textarea');
        textArea.value = url;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        const successful = document.execCommand('copy');
        document.body.removeChild(textArea);
        
        if (successful) {
            showNotification('链接已复制到剪贴板', 'success');
        } else {
            throw new Error('execCommand failed');
        }
    } catch (error) {
        console.error('复制失败:', error);
        
        // 最后的降级方案：显示链接让用户手动复制
        const fallbackText = `无法自动复制，请手动复制以下链接：\n${url}`;
        showNotification(fallbackText, 'warning');
        
        // 尝试使用 prompt 显示链接
        setTimeout(() => {
            const userInput = prompt('请复制以下链接：', url);
            if (userInput !== null) {
                showNotification('请手动复制链接', 'info');
            }
        }, 100);
    }
}

// 关闭结果
function closeResult() {
    elements.resultSection.style.display = 'none';
}

// 重置处理
function handleReset() {
    if (state.isGenerating) return;
    
    // 清空所有输入
    if (elements.editPrompt) elements.editPrompt.value = '';
    if (elements.createPrompt) elements.createPrompt.value = '';
    if (elements.negativePrompt) elements.negativePrompt.value = '';
    if (elements.createNegativePrompt) elements.createNegativePrompt.value = '';
    if (elements.imageUrl) elements.imageUrl.value = '';
    if (elements.imageInput) elements.imageInput.value = '';
    
    // 隐藏图片信息
    if (elements.imageInfo) elements.imageInfo.style.display = 'none';
    if (elements.originalSizeOption) {
        elements.originalSizeOption.style.display = 'none';
        elements.originalSizeOption.selected = false;
    }
    
    // 重置预览
    if (elements.previewImage) elements.previewImage.style.display = 'none';
    if (elements.previewPlaceholder) elements.previewPlaceholder.style.display = 'flex';
    if (elements.createPreviewImage) elements.createPreviewImage.style.display = 'none';
    if (elements.createPreviewPlaceholder) elements.createPreviewPlaceholder.style.display = 'flex';
    
    // 恢复容器默认尺寸
    const previewContainer = document.querySelector('.preview-container');
    const createPreviewContainer = document.querySelector('.create-preview-container');
    if (previewContainer) {
        previewContainer.style.width = '';
        previewContainer.style.height = '';
        previewContainer.style.aspectRatio = '1';
    }
    if (createPreviewContainer) {
        createPreviewContainer.style.width = '';
        createPreviewContainer.style.height = '';
        createPreviewContainer.style.aspectRatio = '1';
    }
    
    // 重置参数
    if (elements.stepsSlider) elements.stepsSlider.value = 50;
    if (elements.guidanceSlider) elements.guidanceSlider.value = 3.5;
    if (elements.seedInput) elements.seedInput.value = 12345;
    updateParameterDisplay();
    
    // 清空状态
    clearCurrentState();
    
    showNotification('已重置所有设置', 'info');
}

// 清空当前状态
function clearCurrentState() {
    state.currentImage = null;
    state.currentImageUrl = null;
    state.uploadedFilename = null;
    state.originalDimensions = null;
    updateStatusIndicator('ready', '就绪');
}

// 更新生成按钮
function updateGenerateButton() {
    if (!elements.generateBtn) return;
    
    elements.generateBtn.disabled = state.isGenerating;
    if (state.isGenerating) {
        elements.generateBtn.innerHTML = '<svg class="loading" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>生成中...';
    } else {
        elements.generateBtn.innerHTML = state.currentMode === 'generate' 
            ? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>开始编辑'
            : '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/></svg>开始生成';
    }
}

// 显示进度
function showProgress() {
    elements.progressContainer.style.display = 'block';
    elements.progressFill.style.width = '0%';
    elements.progressText.textContent = '正在生成中...';
    
    // 模拟进度更新
    let progress = 0;
    const interval = setInterval(() => {
        progress += Math.random() * 15;
        if (progress > 90) progress = 90;
        elements.progressFill.style.width = `${progress}%`;
        
        if (!state.isGenerating) {
            clearInterval(interval);
            elements.progressFill.style.width = '100%';
            elements.progressText.textContent = '生成完成！';
        }
    }, 500);
}

// 隐藏进度
function hideProgress() {
    setTimeout(() => {
        elements.progressContainer.style.display = 'none';
    }, 2000);
}

// 状态指示器更新
function updateStatusIndicator(status, text) {
    const dot = elements.statusIndicator.querySelector('.status-dot');
    const textElement = elements.statusIndicator.querySelector('span');
    
    // 移除所有状态类
    dot.className = 'status-dot';
    
    // 添加新状态类
    switch (status) {
        case 'ready':
            dot.style.background = '#00ff88';
            break;
        case 'uploading':
            dot.style.background = '#ffa726';
            dot.classList.add('loading');
            break;
        case 'image-loaded':
            dot.style.background = '#4facfe';
            break;
        case 'prompt-ready':
            dot.style.background = '#f093fb';
            break;
        case 'generating':
            dot.style.background = '#ff6b6b';
            dot.classList.add('loading');
            break;
        case 'success':
            dot.style.background = '#00ff88';
            break;
        case 'error':
            dot.style.background = '#ff4757';
            break;
    }
    
    textElement.textContent = text;
}

// 通知显示
function showNotification(message, type = 'info') {
    // 支持多行文本
    elements.notificationText.innerHTML = message.replace(/\n/g, '<br>');
    elements.notification.className = `notification ${type}`;
    elements.notification.classList.add('show');
    
    // 根据消息长度调整显示时间
    const displayTime = message.length > 100 ? 5000 : 3000;
    
    setTimeout(() => {
        elements.notification.classList.remove('show');
    }, displayTime);
}

// 键盘快捷键
function handleKeyboard(e) {
    if (e.ctrlKey || e.metaKey) {
        switch (e.key) {
            case 'Enter':
                e.preventDefault();
                if (!state.isGenerating) {
                    handleGenerate();
                }
                break;
            case 'r':
                e.preventDefault();
                handleReset();
                break;
        }
    }
}

// 粒子效果
function createParticles() {
    const particlesContainer = document.getElementById('particles');
    const particleCount = 50;
    
    for (let i = 0; i < particleCount; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        particle.style.left = Math.random() * 100 + '%';
        particle.style.top = Math.random() * 100 + '%';
        particle.style.animationDelay = Math.random() * 6 + 's';
        particle.style.animationDuration = (Math.random() * 3 + 3) + 's';
        particlesContainer.appendChild(particle);
    }
}

// 用户偏好设置
function saveUserPreferences() {
    const preferences = {
        currentMode: state.currentMode,
        model: 'Qwen/Qwen-Image-Edit', // 固定模型
        size: elements.sizeSelect?.value || '1024x1024',
        steps: elements.stepsSlider?.value || 50,
        guidance: elements.guidanceSlider?.value || 3.5,
        generationHistory: state.generationHistory
    };
    
    localStorage.setItem('aiImageGenerator_preferences', JSON.stringify(preferences));
}

function loadUserPreferences() {
    try {
        const saved = localStorage.getItem('aiImageGenerator_preferences');
        if (saved) {
            const preferences = JSON.parse(saved);
            
            // 恢复设置 - 添加空值检查
            if (elements.sizeSelect) elements.sizeSelect.value = preferences.size || '1024x1024';
            if (elements.stepsSlider) elements.stepsSlider.value = preferences.steps || 50;
            if (elements.guidanceSlider) elements.guidanceSlider.value = preferences.guidance || 3.5;
            
            // 恢复历史记录
            if (preferences.generationHistory) {
                state.generationHistory = preferences.generationHistory;
            }
            
            updateParameterDisplay();
        }
    } catch (error) {
        console.error('加载用户偏好失败:', error);
    }
}

// 页面卸载时保存设置
window.addEventListener('beforeunload', saveUserPreferences);

// 定期保存设置
setInterval(saveUserPreferences, 30000); // 每30秒保存一次

// 文件大小格式化
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
